package com.lvtongka.app.ui.webview

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.*
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.alipay.sdk.app.PayTask
import com.google.gson.Gson
import com.icbc.ndf.jft.PayActivity
import com.icbc.ndf.jft.PayActivity.openPayActivity
import com.icbc.ndf.jft.contants.PayResultVO
import com.icbc.ndf.jft.utils.OrderResultCallBack
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.R
import com.lvtongka.app.common.CommonUtils
import com.lvtongka.app.common.NaviUtils
import com.lvtongka.app.databinding.ActivityWebviewBinding
import com.lvtongka.app.helper.SPHelper
import com.lvtongka.app.helper.SPKConstants
import com.lvtongka.app.ui.card.BindCardActivity
import com.lvtongka.app.ui.coupon.bean.CouponItem
import com.lvtongka.app.ui.qr.QrCodeActivity
import com.lvtongka.app.ui.recharge.bean.PayResult
import com.lvtongka.app.ui.webview.bean.AliBean
import com.lvtongka.app.ui.webview.bean.MapBean
import com.lvtongka.app.ui.webview.bean.PhoneBean
import com.lvtongka.app.ui.webview.viewmodel.PaymentViewModel
import java.lang.reflect.InvocationTargetException

class WebViewActivity : BaseActivity<ActivityWebviewBinding, PaymentViewModel>() {
    private var orderId: String? = ""

    companion object {
        const val URL_KEY = "url_key"
        const val TITLE_KEY = "title_key"
        const val IS_TITLE_SHOW_KEY = "is_title_key"
        const val IS_WITHE = "is_withe"
        const val BIND_CARD_REQUEST_CODE = 10
    }

//    private var mTvTitle: TextView? = null
    private var mUrlPath: String? = null
    private var mTitle: String? = null

    private var isTitleShow: Boolean = false
    private var isWithe = false

    override fun initViewModel(): PaymentViewModel {
        return ViewModelProvider(this)[PaymentViewModel::class.java]
    }

    override fun initEvent() {
        binding.imgBack.setOnClickListener {
            finish()
        }
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    binding.progressBar.visibility = View.GONE //加载完网页进度条消失
                } else {
                    binding.progressBar.visibility = View.VISIBLE //开始加载网页时显示进度条
                    binding.progressBar.progress = newProgress //设置进度值
                }
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                //设置当前activity的标题栏
//                mTvTitle?.text = title
                super.onReceivedTitle(view, title)
            }
        }
        binding.webView.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(
                webView: WebView,
                sslErrorHandler: SslErrorHandler,
                sslError: SslError
            ) {
                sslErrorHandler.proceed()
                showToast("网络异常")
            }

            override fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
                webView.loadUrl(url) //加载需要显示的网页
                return true
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                binding.statusBarView.layoutParams.height = CommonUtils.getStatusBarHeight()
                if (isTitleShow) {
                    binding.rlAppTitle.visibility = View.VISIBLE
                } else {
                    binding.rlAppTitle.visibility = View.GONE
                }
                if (isWithe)
                    binding.statusBarView.setBackgroundColor(Color.WHITE)
                evaluate()
            }
        }
        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
        }
    }

    override fun initData() {
        mUrlPath = intent.getStringExtra(URL_KEY)
        mTitle = intent.getStringExtra(TITLE_KEY)
        if (intent.hasExtra(IS_TITLE_SHOW_KEY)) {
            isTitleShow = intent.getBooleanExtra(IS_TITLE_SHOW_KEY, false)
        }
        if (intent.hasExtra(IS_WITHE)) {
            isWithe = intent.getBooleanExtra(IS_WITHE, false)
        }
        initSetting(binding.webView)
//        WebView.setWebContentsDebuggingEnabled(true);

        binding.webView.addJavascriptInterface(JsInterface(), "NativeBridge")
        evaluate()
        binding.webView.loadUrl(mUrlPath + "")
    }

    private fun evaluate() {
        val dataToPass = SPHelper.getString(SPKConstants.LOGIN_ACCESS_TOKEN)
        val script = "window.localStorage.setItem('LTK_ACCESS_TOKEN', '$dataToPass');"
        binding.webView.evaluateJavascript(script, null)
    }

    override fun initBinding(): ActivityWebviewBinding {
        return ActivityWebviewBinding.inflate(layoutInflater)
    }

    private fun initSetting(webView: WebView) {
        webView.settings.javaScriptCanOpenWindowsAutomatically = true
        webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.settings.setGeolocationEnabled(true)
        webView.settings.databaseEnabled = true
        webView.settings.allowFileAccess = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }
        webView.settings.blockNetworkImage = false
        webView.settings.savePassword = true
        webView.settings.setSupportZoom(true)
        webView.settings.builtInZoomControls = false
        webView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webView.settings.useWideViewPort = true
        try { //本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
            if (Build.VERSION.SDK_INT >= 16) {
                val clazz: Class<*> = webView.settings.javaClass
                val method = clazz.getMethod(
                    "setAllowUniversalAccessFromFileURLs", Boolean::class.javaPrimitiveType
                )
                if (method != null) {
                    method.invoke(webView.settings, true)
                }
            }
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }
        webView.settings.allowUniversalAccessFromFileURLs = true
        webView.settings.defaultTextEncodingName = "utf-8" //文本编码
    }

    /**
     * 支付结果返回 回到当前界面之后调用此方法通知js支付成功
     */
    private fun requestJs(json: String) {
        binding.webView.evaluateJavascript(
            "javascript:paymentCallback($json)"
        ) {
            Log.d(WebViewActivity::class.java.name, "回调：$it")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1) {
            // 处理支付结果回调 使用从外部返回的 或者 自己拼接 目前就是一个string类型
            requestJs(orderId!!)
        }
        if (requestCode == BIND_CARD_REQUEST_CODE && resultCode == RESULT_OK) {
            // 绑卡回调 刷新界面
            binding.webView.reload()
        }
        if (requestCode == 113 && resultCode == RESULT_OK) {
            binding.webView.reload()
        }
    }

    inner class JsInterface {
        @JavascriptInterface
        fun createBingCardFunc() {
            startActivityForResult(Intent(this@WebViewActivity, BindCardActivity::class.java), BIND_CARD_REQUEST_CODE)
        }

        @JavascriptInterface
        fun backFunc() {
            finish()
        }

        @JavascriptInterface
        fun alipayFunc(json: String) {
            val bean = Gson().fromJson(json, AliBean::class.java)
            when (bean.payType) {
                "3", "6" ->{
                    confirmPay(bean.jumpUrl)
                }
                "4" -> {
                    getAilPay(bean.jumpUrl)
                }
            }
        }

        @JavascriptInterface
        fun mapFunc(json: String) {
            val bean = Gson().fromJson(json, MapBean::class.java)
            showMapList(bean)
        }

        @JavascriptInterface
        fun callPhoneNumber(json: String) {
            val bean = Gson().fromJson(json, PhoneBean::class.java)
            val intent = Intent(Intent.ACTION_DIAL)
            val data = Uri.parse("tel:${bean.phone}")
            intent.data = data
            startActivity(intent)
        }

        @JavascriptInterface
        fun couponQRCodeFunc(json: String) {
            // 跳转券
            val itemBean = Gson().fromJson(json, CouponItem::class.java)
            // 跳转到二维码界面
            startActivityForResult(
                Intent(
                    this@WebViewActivity,
                    QrCodeActivity::class.java
                ).apply {
                    putExtra("coupon", itemBean)
                }, 113
            )
        }
    }

    private fun showMapList(map: MapBean) {
        var mapNames = mutableListOf("百度地图", "高德地图")
        val builder = AlertDialog.Builder(this)
            .setTitle("选择地图")
            .setItems(mapNames.toTypedArray()) { dialog, which ->
                when (which) {
                    0 -> {
                        NaviUtils.selectBD(this,map.lat, map.lon,"我的位置", map.address)
                    }
                    1 -> {
                        NaviUtils.selectGD(this,map.lat, map.lon,"我的位置", map.address)
                    }
                }
            }
        builder.create().show()
    }

    private fun confirmPay(trim: String) {
        openPayActivity(this, trim,
            object : OrderResultCallBack {
                override fun onSuccess(payResultVO: PayResultVO) {
                    PayActivity.finishPayActivity()
                    showToast("支付成功")
                    binding.webView.reload()
                }

                override fun onError(payResultVO: PayResultVO) {
//                    showToast("onError" + payResultVO.tranCode)
                    PayActivity.finishPayActivity()
                    binding.webView.reload()
                }
            })
    }

    private fun getAilPay(payData: String) {
        // 完整的符合支付宝参数规范的订单信息
        val payRunnable = Runnable { // 构造PayTask 对象
            val alipay = PayTask(this@WebViewActivity)
            // 调用支付接口，获取支付结果
            val result = alipay.pay(payData, true)

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            handle.sendMessage(msg)
        }
        // 必须异步调用
        Thread(payRunnable).start()
    }

    private val SDK_PAY_FLAG: Int = 1
    @SuppressLint("HandlerLeak")
    private val handle = Handler { msg ->
        when (msg.what) {
            SDK_PAY_FLAG -> {
                if (msg.obj is Map<*, *>) {
                    @SuppressWarnings("unchecked")
                    val payResult = PayResult(msg.obj as Map<String, String>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // resultStatus={9000};memo={};result={{"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2021004199650878","auth_app_id":"2021004199650878","charset":"UTF-8","timestamp":"2024-12-04 10:09:46","out_trade_no":"1_1864129913250983937","total_amount":"0.01","trade_no":"2024120422001401751415025114","seller_id":"2088641231292273"},"sign":"enc1DhlFAGR9C43bASvPocDTLthkJ/flAZU0nxbmMnesNkA+H0d6Ek60b8NbVzVqU+RbBOqWbpDqXHgmXDs27aBvQP0iiiEduC44QzEi6YWi2WoMBJSkttyEky8aPaYUxJbKbi2GcbIAQ7Q7Vogvj8qPpiXpxl4Ht7TocV+EjnOqoZhldypdBnTSr3uovgM5+dgy8OOvqbDP/gFXkAeY1Nh3++bi24/vWYVHC7nidN5G7RzzPX6rOH5jEEoK8dhFsrown8vEr/gbE/sHOqXk7uRy8F6SWt1qgQ0emaQqT7n87BiX7d6D4QRhRpHjCaRCajuNc6T3BhlrWPpFSKpVBw==","sign_type":"RSA2"}};extendInfo={{"doNotExit":true,"isDisplayResult":true,"tradeNo":"2024120422001401751415025114"}}
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showToast("支付成功")
                        binding.webView.reload()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        binding.webView.reload()
                    }
                } else {
                    // 解析
                    var sp = msg.obj.toString().split(";")
                    if (sp.size > 1) {
                        var status = sp[0].substring(sp[0].indexOf("{") + 1, sp[0].lastIndexOf("}"))
                        if (TextUtils.equals(status, "9000")) {
                            binding.webView.reload()
                        }
                    }
                }
            }
        }
        false
    }

    override fun onDestroy() {
        binding.webView.removeJavascriptInterface("NativeBridge")
        isBlack = false
        super.onDestroy()
    }

    override fun onBackPressed() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
            binding.webView.removeAllViews()
        } else {
            super.onBackPressed()
        }
    }
}